package cn.xutongxue.interview.job.single;

import cn.hutool.core.collection.CollUtil;
import cn.xutongxue.interview.entity.Question;
import cn.xutongxue.interview.es.dao.QuestionEsDao;
import cn.xutongxue.interview.es.entity.QuestionEsEntity;
import cn.xutongxue.interview.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 单次全量同步题目数据到Es
 * @author Administrator
 */
// @Component
@Slf4j
public class FullSyncQuestionToEs implements CommandLineRunner {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionEsDao questionEsDao;

    @Override
    public void run(String... args) throws Exception {
        // 全量获取题目数据，数据量不大可以直接获取到内存中
        List<Question> questionList = questionService.list();
        if (CollUtil.isEmpty(questionList)) {
            return;
        }
        // 数据类型转换
        List<QuestionEsEntity> questionEsEntityList = questionList.stream().map(QuestionEsEntity::objToEsEntity).collect(Collectors.toList());
        // 分页导入ES
        final int pageSize = 500;
        int total = questionEsEntityList.size();
        log.info("FullSyncQuestionToEs start, total num:{}", total);
        for (int i = 0; i < pageSize; i += pageSize) {
            // 防止下标超过数据总数
            int end = Math.min(i + pageSize, total);
            log.info("sync from {}, to {}", i, end);
            questionEsDao.saveAll(questionEsEntityList.subList(i, end));
        }
        log.info("FullSyncQuestionToEs end, total num:{}", total);
    }
}
